<?php
class comment_model_thread extends Model {
	public function __construct(){
		parent::__construct();
		$this->table = 'app_com_thread';
	}
	//添加一个主题贴
	public function add_thread($arguments){
		$arguments = filter_params($arguments,'res_id','author_id');
		trim_params($arguments);		
		$arguments['create_time'] = time();
		$arguments['reply_time'] = time();	
		$arguments['deleted'] = 0;
		
		return $this->db->insert($this->table, $arguments); 
	}
	
	/**
	 * 获取资源最新的前N条评论
	 *
	 * @param unknown_type $res_id
	 * @param unknown_type $num
	 */
	public function getResCommentNew($res_id,$num = 3){
		!$num && $num = 3;
		$sql = "SELECT * FROM $this->table WHERE res_id='$res_id' AND deleted=0 ORDER BY thread_id DESC LIMIT $num ";
		return $this->db->fetchAll($sql);
	}
	
	//读取一个资源下的主题
	public function get_thread($res_id){
		
		$sql = "select * from ".$this->table." where res_id=&res_id and deleted=&deleted";
		$params = array('res_id'=>$res_id,'deleted'=>'0');
		return $result = $this->db->fetchALL($sql, $params);
	}
	//读取一个主题的相关信息
	public function get_thread_data($thread_id){
		$sql = "select * from ".$this->table." where thread_id=&thread_id order by reply_time desc";
		$params = array('thread_id'=>$thread_id);
		return $result = $this->db->fetchRow($sql, $params);
		
	}
	//  删除一个主题
	public function delete_thread_data($thread_id){
		$sql = "update ".$this->table." set deleted=deleted+1 where thread_id=&thread_id";
		$params = array('thread_id'=>$thread_id);
		$this->db->query($sql, $params);
	}
	//修改主题贴的 回复时间
	public function update_reply_time($thread_id){
		$reply_time = time();
		$sql = "update ".$this->table." set reply_time=$reply_time where thread_id=&thread_id";
		$params = array('thread_id'=>$thread_id);
		$this->db->query($sql, $params);
	}
	//取得主题贴 按最新回复时间
	public function thread_new_comment($res_id){
		$num = count($res_id);
		for($i=0;$i<$num;$i++){
			$sql = "select * from ".$this->table." where res_id=&res_id and deleted=&deleted order by reply_time desc";
			$params = array('res_id'=>$res_id[$i]['res_id'],'deleted'=>0);
			$result[$i] = $this->db->fetchAll($sql, $params);
			array_push($result[$i],$res_id[$i]);
		}
		return $result;
	}
	
}